package com.chase.springboot.service.impl;

import com.chase.springboot.mapper.*;
import com.chase.springboot.model.Menu;
import com.chase.springboot.model.Role;
import com.chase.springboot.model.User;
import com.chase.springboot.model.UserRole;
import com.chase.springboot.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<Role> getRolesByUserId(Integer userId) {
        List<Integer> roleIds = userRoleMapper.getRoleIdsByUserId(userId);
        if (roleIds == null || roleIds.size() == 0) return null;
        return roleMapper.getRolesByIds(roleIds);
    }

    @Override
    public Boolean addRoleToUser(Integer roleId, Integer userId) {
        //先判读id是否存在
        Role role = roleMapper.selectByPrimaryKey(roleId);
        if (role == null) return false;
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) return false;
        //添加关联
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        int i = userRoleMapper.insert(userRole);
        return i > 0;
    }

    @Override
    public Boolean deleteRoleByUserId(Integer userId) {
        return userRoleMapper.deleteByUserId(userId);
    }

    @Override
    public List<User> getUsersByRoleId(Integer roleId) {
        List<Integer> userIds = userRoleMapper.getUserIdsByRoleId(roleId);
        if (userIds == null || userIds.size() == 0) return null;
        return userMapper.getUsersByIds(userIds);
    }

    @Override
    public Boolean addUserToRole(Integer userId, Integer roleId) {
        return this.addRoleToUser(roleId, userId);
    }

    @Override
    public Boolean deleteUserByRoleId(Integer roleId) {
        return userRoleMapper.deleteByRoleId(roleId);
    }

    @Override
    public List<Menu> getMenusByUserId(Integer userId) {
        List<Integer> roleIds = userRoleMapper.getRoleIdsByUserId(userId);
        List<Integer> menuIds = new ArrayList<>(); //此处可以用set去重，但结果是一样的
        for (Integer id : roleIds){
            List<Integer> ids = roleMenuMapper.selectMenuIdsByRoleId(id);
            menuIds.addAll(ids);
        }
        if (menuIds == null || menuIds.size() == 0) return null;
        return menuMapper.selectByMenuIds(menuIds);
    }
}
